package com.szty.mod_jyzs.web

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.webkit.WebView
import android.widget.LinearLayout
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.KeyboardUtils
import com.gyf.immersionbar.ImmersionBar
import com.just.agentweb.AgentWeb
import com.just.agentweb.AgentWebConfig
import com.just.agentweb.WebViewClient
import com.sjh.baseui.dialog.CustomProgressDialog
import com.sjh.baseutils.bugly.BugReport
import com.sjh.lib_app.AppConfig
import com.sjh.lib_app.baseui.BaseActivity
import com.sjh.lib_app.net.HeadInfoInterceptor
import com.sjh.lib_update.AppUpDateManage
import com.sjh.lib_update.UpDataBean
import com.sjh.net.interceptor.HttpInfoCatchInterceptor
import com.szty.mod_jyzs.R
import kotlinx.android.synthetic.main.jyzs_activity_web.*
import java.io.File


@Route(path = "/jyzs/web", name = "web页")
class WebActivity : BaseActivity() {
    var mAgentWeb: AgentWeb? = null
    private val REQUEST_LOCAL_PERMISSIONCODE = 133
    val pd by lazy {
        CustomProgressDialog.createDialog(this).apply {
            setCanceledOnTouchOutside(true)
            closeOutSideWindow(true)
            setMessage(context.getString(R.string.dl_waiting))
        }
    }
    private val webViewClient by lazy {
        object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                pd.show()
            }

            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                if (pd.isShowing) pd.dismiss()
            }
        }
    }


    override fun onCreateRootView() = R.layout.jyzs_activity_web

    override fun onInitView(savedInstanceState: Bundle?) {
        ImmersionBar.with(this).statusBarDarkFont(true)
            .init()
        initAgentWeb()
    }

    override fun initListener() {
    }

    override fun initData() {
        KeyboardUtils.registerSoftInputChangedListener(this) {
            if (it == 0) {
                //键盘收起
                mAgentWeb?.jsAccessEntrace?.quickCallJs("keyboardCollapsed")
            } else {
                //键盘展开
                mAgentWeb?.jsAccessEntrace?.quickCallJs("keyboardExpansion", it.toString())
            }
        }
        checkUpdata()
    }

    private fun checkUpdata() {
        AppUpDateManage.getInstance().checkApk(mLifecycle = lifecycle,
            preBlock = {
                this.setDefaultInterceptors(
                    arrayListOf(
                        HttpInfoCatchInterceptor(),
                        HeadInfoInterceptor()
                    )
                )
                this.baseUrl = AppConfig.getAppUrl()
            },
            mParams = mapOf(
                "type" to AppConfig.environmentTag.toLowerCase(),
                "platform" to AppConfig.env.channelName
                )
            ,
            isReturn = true,
            compiler = {},
            showUpdateDialog = { file: File, apkInfoBean: UpDataBean ->

            })

    }

    override fun onPause() {
        mAgentWeb?.webLifeCycle?.onPause()
        super.onPause()
    }

    override fun onResume() {
        mAgentWeb?.webLifeCycle?.onResume()
        super.onResume()
    }

    override fun onDestroy() {
        mAgentWeb?.webLifeCycle?.onDestroy()
        super.onDestroy()
    }

    private fun initAgentWeb() {
        mAgentWeb = AgentWeb.with(this)
            .setAgentWebParent(ll_parent, LinearLayout.LayoutParams(-1, -1))
            .useDefaultIndicator(Color.TRANSPARENT, 0)   //进度条，第一个参数是进度条的颜色，第二个参数是进度条的高度，这里需要隐藏进度条
            .setMainFrameErrorView(
                R.layout.jyzs_activity_web_err,
                -1
            ) //参数1是错误显示的布局，参数2点击刷新控件ID -1表示点击整个布局都刷新， AgentWeb 3.0.0 加入。
            .setWebViewClient(webViewClient)
            .createAgentWeb()
            .ready()
            .go(AppConfig.getWebUrl())
        mAgentWeb?.jsInterfaceHolder?.addJavaObject(
            "android",
            AndroidInterface()
        )
        BugReport.initJavaScriptBugReport(mAgentWeb!!.webCreator.webView,true);
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        mAgentWeb?.let {
            if (it.handleKeyEvent(keyCode, event)) {
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }
    fun getWebToken(){
         mAgentWeb?.jsAccessEntrace?.quickCallJs("getToken",{
                if(it.isNotEmpty()){
                    //TODO 保存token未做
                }
        })
    }
}

fun clearWebCache(context: Context) {
    AgentWebConfig.clearDiskCache(context)
    AgentWebConfig.removeAllCookies()
}